package logic

import (
	"cart_srv/models/mysql"
	"cart_srv/models/redis"
	"context"
	"errors"

	"cart_srv/cart_srv"
	"cart_srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateCartLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateCartLogic {
	return &CreateCartLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateCartLogic) CreateCart(in *cart_srv.CreateCartRequest) (*cart_srv.CreateCartResponse, error) {
	// todo: add your logic here and delete this line
	goods, err := mysql.GetGoods(int(in.ShopId))
	if err != nil {
		return nil, errors.New("购物车添加失败,商品不存在")
	}
	if goods.ID == 0 {
		return nil, errors.New("购物车添加失败,商品不存在")
	}

	stock := redis.GetStock(int(in.ShopId))

	if stock < in.Num {
		return nil, errors.New("购物车添加失败,商品库存不足")
	}

	if !redis.FindCart(int(in.UserId), int(in.ShopId)) {
		var cart = map[string]interface{}{
			"user_id":     in.UserId,
			"shop_id":     in.ShopId,
			"goods_num":   in.Num,
			"goods_name":  goods.GoodsName,
			"goods_cover": goods.GoodsCover,
			"goods_intro": goods.GoodsIntro,
			"goods_price": goods.GoodsPrice,
			"checked":     1,
		}
		err = redis.CreateCart(int(in.UserId), int(in.ShopId), cart)
		if err != nil {
			return nil, errors.New("购物车添加失败")
		}
	} else {
		err = redis.UpdateCart(int(in.UserId), int(in.ShopId), int(in.Num))
		if err != nil {
			return nil, errors.New("购物车添加失败")
		}
	}

	return &cart_srv.CreateCartResponse{}, nil
}
